const express = require('express');
const router = express.Router();
const { authenticateAdmin } = require('../../middleware/auth');
const ResponseHelper = require('../../utils/response');
const ExposurePrisma = require('../../models/ExposurePrisma');

// 获取曝光台统计信息
router.get('/stats', authenticateAdmin, async (req, res) => {
  try {
    const stats = await ExposurePrisma.getStats();
    return ResponseHelper.success(res, stats, '获取统计信息成功');
  } catch (err) {
    console.error('获取统计信息失败:', err);
    return ResponseHelper.serverError(res, '获取统计信息失败', err);
  }
});

// 获取曝光台帖子列表
router.get('/posts', authenticateAdmin, async (req, res) => {
  try {
    const {
      page = 1,
      pageSize = 10,
      search,
      startDate,
      endDate,
      sortBy = 'created_at',
      sortOrder = 'desc'
    } = req.query;

    const filters = {
      page: parseInt(page),
      pageSize: parseInt(pageSize),
      search,
      startDate,
      endDate,
      sortBy,
      sortOrder
    };

    const result = await ExposurePrisma.getAdminPostsList(filters);
    
    return ResponseHelper.success(res, {
      items: result.posts,
      total: result.pagination.total_count,
      page: result.pagination.current_page,
      pageSize: result.pagination.page_size
    }, '获取曝光台帖子列表成功');
  } catch (err) {
    console.error('获取曝光台帖子列表失败:', err);
    return ResponseHelper.serverError(res, '获取曝光台帖子列表失败', err);
  }
});

// 获取单个帖子详情
router.get('/posts/:id', authenticateAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    const post = await ExposurePrisma.getPostById(id);

    if (!post) {
      return ResponseHelper.notFound(res, '帖子不存在');
    }

    return ResponseHelper.success(res, post, '获取帖子详情成功');
  } catch (err) {
    console.error('获取帖子详情失败:', err);
    return ResponseHelper.serverError(res, '获取帖子详情失败', err);
  }
});

// 编辑帖子
router.put('/posts/:id', authenticateAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    const { content, images } = req.body;

    if (!content || content.trim().length === 0) {
      return ResponseHelper.error(res, '帖子内容不能为空', 400);
    }

    if (content.length > 2000) {
      return ResponseHelper.error(res, '帖子内容不能超过2000字', 400);
    }

    if (images && images.length > 9) {
      return ResponseHelper.error(res, '最多只能上传9张图片', 400);
    }

    const post = await ExposurePrisma.getPostById(id);
    if (!post) {
      return ResponseHelper.notFound(res, '帖子不存在');
    }

    const updatedPost = await ExposurePrisma.updatePost(id, {
      content: content.trim(),
      images: images || []
    });

    return ResponseHelper.success(res, updatedPost, '编辑帖子成功');
  } catch (err) {
    console.error('编辑帖子失败:', err);
    return ResponseHelper.serverError(res, '编辑帖子失败', err);
  }
});

// 删除帖子
router.delete('/posts/:id', authenticateAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    
    const post = await ExposurePrisma.getPostById(id);
    if (!post) {
      return ResponseHelper.notFound(res, '帖子不存在');
    }

    await ExposurePrisma.deletePost(id);
    return ResponseHelper.success(res, null, '删除帖子成功');
  } catch (err) {
    console.error('删除帖子失败:', err);
    return ResponseHelper.serverError(res, '删除帖子失败', err);
  }
});

// 获取帖子评论列表
router.get('/posts/:id/comments', authenticateAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    const { page = 1, pageSize = 20 } = req.query;

    const result = await ExposurePrisma.getCommentsByPostId(id, parseInt(page), parseInt(pageSize));
    return ResponseHelper.success(res, result, '获取评论列表成功');
  } catch (err) {
    console.error('获取评论列表失败:', err);
    return ResponseHelper.serverError(res, '获取评论列表失败', err);
  }
});

// 删除评论
router.delete('/comments/:id', authenticateAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    
    await ExposurePrisma.deleteComment(id);
    return ResponseHelper.success(res, null, '删除评论成功');
  } catch (err) {
    console.error('删除评论失败:', err);
    if (err.message === '评论不存在') {
      return ResponseHelper.notFound(res, '评论不存在');
    }
    return ResponseHelper.serverError(res, '删除评论失败', err);
  }
});

module.exports = router;